﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Data.Models.Org;
using System.Web.Security;
using ZHDJ.Core;
using ZHDJ.Data;
using ZHDJ.Data.DataCaching;
using ZHDJ.Core.Log;

namespace ZHDJ.Web.PortalParts
{
    public partial class Notice : System.Web.UI.UserControl
    {
        /// <summary>
        /// 数据访问 
        /// </summary>
        public static AppBoxContext DB
        {
            get
            {
                if (!HttpContext.Current.Items.Contains("__AppBoxContext"))
                {
                    HttpContext.Current.Items["__AppBoxContext"] = new AppBoxContext();
                }
                return HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext;
            }
        }

        /// <summary>
        /// 网站域名
        /// </summary>
        public string WebHost
        {
            get { return SystemParameterCaching.Get(SystemParameterKey.WebHost); }
        }

        private PartyOrgMember _CurrentUser
        {
            get { return Session["_CurrentUser_"] as PartyOrgMember; }
            set { Session["_CurrentUser_"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        public void LoadData()
        {
            var login = IsLogin;
            this.noLogin.Visible = !login;
            this.logined.Visible = login;

            if (login)
            {
                litUserName.Text = CurrentUser.UserName;
                this.litBranchMain.Visible = CurrentUser.ManageBranchIDs.Count > 0;
                this.litMain.Visible = IsSystemAdmin;
                var isBuzhan = GetIdentityRoleIDs()
                    .Contains(SystemParameterCaching.Get(SystemParameterKey.BuzhangRoleID));
                litBuzhang.Visible = isBuzhan && !IsSystemAdmin;
            }
        }

        /// <summary>
        /// 当前登陆用户
        /// </summary>
        public PartyOrgMember CurrentUser
        {
            get
            {
                if (this.Page.User.Identity.IsAuthenticated)
                {
                    if (_CurrentUser != null)
                    {
                        return _CurrentUser;
                    }

                    var temp = DB.PartyOrgMembers.Find(Convert.ToString(this.Page.User.Identity.Name));
                    temp.ManageBranchIDs = new List<string>();
                    var dt = PartyOrg.GetBranchManageByLoginId(temp.LoginID);
                    foreach (DataRow dr in dt.Rows)
                    {
                        temp.ManageBranchIDs.Add(Convert.ToString(dr["BranchID"]));
                    }
                    _CurrentUser = temp;

                    return _CurrentUser;
                }
                return null;
            }
        }

        /// <summary>
        ///是否已登陆
        /// </summary>
        public bool IsLogin
        {
            get { return CurrentUser != null && !string.IsNullOrEmpty(CurrentUser.LoginID); }
        }

        /// <summary>
        /// 是否为系统管理员
        /// </summary>
        public bool IsSystemAdmin
        {
            get
            {
                if (CurrentUser.LoginID == "admin")
                {
                    return true;
                }
                var roles = GetIdentityRoleIDs();
                return roles.Contains(SystemParameterCaching.Get(SystemParameterKey.SystemAdminRoleID));
            }
        }

        /// <summary>
        /// 当前登陆用户的角色列表
        /// </summary>
        /// <returns></returns>
        protected List<string> GetIdentityRoleIDs()
        {
            List<string> roleIDs = new List<string>();

            if (this.Page.User.Identity.IsAuthenticated)
            {
                FormsAuthenticationTicket ticket = ((FormsIdentity) this.Page.User.Identity).Ticket;
                string userData = ticket.UserData;

                foreach (string roleID in userData.Split(','))
                {
                    if (!String.IsNullOrEmpty(roleID))
                    {
                        roleIDs.Add(roleID);
                    }
                }
            }

            return roleIDs;
        }

        /// <summary>
        /// 用户登陆日志ID
        /// </summary>
        public string UserLogID
        {
            get
            {
                if (!IsLogin)
                {
                    return "";
                }
                if (Session["UserLogID"] != null)
                {
                    return Session["UserLogID"].ToString();
                }
                else
                {

                    var temp = DB.PartyUserLoginLogs.Where(a => a.LoginID == CurrentUser.LoginID)
                        .OrderByDescending(a => a.LoginTime)
                        .FirstOrDefault();
                    if (temp != null)
                    {
                        Session["UserLogID"] = temp.ID;
                        return temp.ID;
                    }
                    else
                        return "";

                }
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLoginOut_Click(object sender, EventArgs e)
        {

            try
            {
                var userLog = DB.PartyUserLoginLogs.FirstOrDefault(a => a.ID == UserLogID);
                if (userLog != null)
                {
                    userLog.LastOpTime = DateTime.Now;
                    userLog.LoginOutTime = userLog.LastOpTime;
                    DB.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog("用户退出", ex);
            }

            FormsAuthentication.SignOut();
            Session.Abandon();
            //回到首页
            Response.Redirect(WebHost + "/default.aspx");

        }
    }
}